using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour, ISavable
{
    public static GameManager Instance { get; private set; }
    private Checkpoint[] checkpoints;
    public Vector3 playerLastPosition;
    [Header("Lost currency")]
    [SerializeField] private GameObject lostCurencyPrefab;
    public int lostCurrencyAmount;
    [SerializeField] private float lostCurrencyX;
    [SerializeField] private float lostCurrencyY;

    private void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
        checkpoints = FindObjectsByType<Checkpoint>(FindObjectsSortMode.None);
        lostCurencyPrefab = Resources.Load<GameObject>("Prefabs/LostCurrency");
    }

    public void RestartScene()
    {
        SaveManager.Instance.Save();
        Scene scene = SceneManager.GetActiveScene();
        SceneManager.LoadScene(scene.name);
    }

    public void Load(GameData data)
    {
        _ = StartCoroutine(LoadWithDelay(data));
    }

    // private void PlacePlayerToClosestCheckpoint(GameData data)
    // {
    //     if (data.closestCheckpointId == string.Empty)
    //     {
    //         return;
    //     }
    //
    //     data.closestCheckpointId = FindClosestCheckpoint(data.lastPosition)?.id ?? string.Empty;
    //     foreach (Checkpoint checkpoint in Checkpoints)
    //     {
    //         if (data.closestCheckpointId == checkpoint.id)
    //         {
    //             PlayerManager.Instance.Player.transform.position = checkpoint.Locator.position;
    //         }
    //     }
    // }

    private void LoadCheckpoints(GameData data)
    {
        foreach (System.Collections.Generic.KeyValuePair<string, bool> pair in data.checkpoints)
        {
            foreach (Checkpoint checkpoint in checkpoints)
            {
                if (checkpoint.id == pair.Key && pair.Value)
                {
                    checkpoint.ActivateCheckpoint();
                }
            }
        }
    }

    private void LoadLostCurrency(GameData data)
    {
        lostCurrencyAmount = data.lostCurrencyAmount;
        lostCurrencyX = data.lostCurrencyX;
        lostCurrencyY = data.lostCurrencyY;
        if (lostCurrencyAmount > 0)
        {
            GameObject obj = Instantiate(lostCurencyPrefab, new Vector3(lostCurrencyX, lostCurrencyY, 0f), Quaternion.identity);
            obj.GetComponent<LostCurrencyController>().currency = lostCurrencyAmount;
        }
        lostCurrencyAmount = 0; // Reset after loading to avoid duplication
    }

    private IEnumerator LoadWithDelay(GameData data)
    {
        yield return new WaitForSeconds(0.1f);
        LoadCheckpoints(data);
        // PlacePlayerToClosestCheckpoint(data);
        LoadLostCurrency(data);
    }

    public void Save(ref GameData data)
    {
        data.lostCurrencyAmount = lostCurrencyAmount;
        data.lostCurrencyX = PlayerManager.Instance.transform.position.x;
        data.lostCurrencyY = PlayerManager.Instance.transform.position.y;
        // data.closestCheckpointId = FindClosestCheckpoint(data.lastPosition)?.id ?? string.Empty;
        data.checkpoints.Clear();
        foreach (Checkpoint checkpoint in checkpoints)
        {
            data.checkpoints.Add(checkpoint.id, checkpoint.isActive);
        }
    }

    public Checkpoint FindClosestCheckpoint(Vector3 position)
    {
        Checkpoint closest = null;
        float closestDistance = float.MaxValue;
        foreach (Checkpoint checkpoint in checkpoints)
        {
            if (!checkpoint.isActive) continue;
            float distance = Vector3.Distance(position, checkpoint.transform.position);
            if (distance >= closestDistance) continue;
            closestDistance = distance;
            closest = checkpoint;
        }
        return closest;
    }

    public void Pause(bool pause)
    {
        Time.timeScale = pause ? 0f : 1f;
    }
}